package com.enterprise.web;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.assg2.dao.*;
import com.movie.Movie;
import com.movie.Recommend;
import com.movie.Viewer;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;

/**
 * This is the command that will be used for logging in users.
 * If logon is successful, the command should place a list of contacts
 * in the request attriubutes.
 * @author  yunki
 */
public class RecommendCommand implements Command {

    /** Creates a new instance of LoginCommand */
    public RecommendCommand() {
    }

    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //TODO: set the response content type to "text/html" here
        //TODO: You'll have to use getWriter() to output some HTML texts
        //TODO: close the output stream


        response.setContentType("text/html");// from response, set content type
        PrintWriter out = response.getWriter();// from response, get output writer

        HttpSession session = request.getSession(true);


        DaoMovie daomovie = new DaoMovie();
        DaoViewer daoviewer = new DaoViewer();
        DaoRecommend daorecommend = new DaoRecommend();



        //return "//header.html").include(request, response);


        if (request.getParameter("movieid") != null) {

            Movie movie = (Movie) daomovie.findById(Integer.parseInt(request.getParameter("movieid")));
            session.setAttribute("movie", movie);
            return "/recommend.jsp";
        }

        Viewer viewer = (Viewer) session.getAttribute("user");
        Movie movie = (Movie) session.getAttribute("movie");


        String[] friends = request.getParameterValues("friends");

        String prueba = "";
        for (int i = 0; i < friends.length; i++) {
            Integer id = Integer.parseInt(friends[i]);
            Viewer friend = (Viewer) daoviewer.findById(id);
            Recommend recommend = new Recommend(viewer, friend, movie);
            if (!viewer.getRecommend().contains(recommend)) {
                daorecommend.save(recommend);
            }
        }

        request.setAttribute("message", "Movie " + movie.getTitle() + " recommended Succesfully:<a href='dispatcher?operation=login'>Go to index</a>");
        return "message";

    }
}
